import { Injectable, Logger, Req, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/user/entities/user.entity';
import { removeUserData } from 'src/utils';
import { Repository } from 'typeorm';

@Injectable()
export class AuthService {
  private logger = new Logger('AuthService');

  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(account: string, password: string): Promise<User | null> {
    // 查询数据库来验证用户
    const user: User = await this.userRepository.findOne({
      where: { account, isDeleted: 0 },
    });
    // 如果有用户再验证密码
    if (
      user &&
      user.account === account &&
      (await user.validatePassword(password))
    ) {
      delete user.passwordHash;
      delete user.isDeleted;
      return user;
    }
    return null;
  }

  // 生成 Token
  async createToken(data) {
    return await this.jwtService.signAsync(data);
  }

  async login(user: any) {
    const payload = {
      account: user.account,
      userId: user.id,
      roleId: user.roleId,
      roleType: user.roleType,
      roleWeight: user.roleWeight,
    };
    const token = await this.createToken(payload);
    return {
      token,
    };
  }

  // 查询当前账户信息
  async queryCurrentUser(@Req() req) {
    try {
      if (req?.user?.userId) {
        const user = await this.userRepository.findOneBy({
          id: req.user.userId,
        });

        return removeUserData(user);
      }
    } catch (error) {
      this.logger.error('@@@@ 当前登录信息过期，请重新登录:', error);
      throw new UnauthorizedException('当前登录信息过期，请重新登录');
    }
  }
}
